<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>API接口</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 搜索筛选 -->
    <el-form :inline="true" class="user-search">
      <el-form-item label="搜索：">
      </el-form-item>
      <el-form-item label="" v-for="(filter, index) in searchParams.filters" :key="index">
        <el-input size="small" v-model="filter.fieldValue" v-bind:fieldName="filter.fieldName" v-if="filter.showAble"
                  v-bind:fieldValue="filter.fieldValue" v-bind:compare="filter.compare" :disabled="filter.readonly"
                  @keyup.enter.native="search"
                  :placeholder="filter.placeholder" :readonly="filter.readonly" clearable/>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="search()">搜索</el-button>
      </el-form-item>
    </el-form>

    <!--列表-->
    <el-table size="small" :data="list" highlight-current-row v-loading="loading" border
              element-loading-text="拼命加载中"
              style="width: 100%;" :header-row-style="{width: '100%', color: 'darkorange'}">
      <el-table-column align="center" type="selection" width="60">
      </el-table-column>
      <el-table-column align="center" prop="sourceId" label="数据源" width="100">
      </el-table-column>
      <el-table-column align="center" prop="schemaName" label="模式" width="100">
      </el-table-column>
      <el-table-column align="center" prop="tableName" label="表名称" width="170">
      </el-table-column>
      <el-table-column align="center" prop="requestName" label="接口名称" width="130">
      </el-table-column>
      <el-table-column align="center" prop="requestUrl" label="接口地址">
      </el-table-column>
      <el-table-column align="center" prop="requestMethod" label="请求方式" width="80">
      </el-table-column>
      <el-table-column align="center" prop="requestParams" label="参数类型" width="100">
      </el-table-column>
      <el-table-column align="center" label="操作" width="150">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">修改</el-button>

          <el-button size="mini" @click="handleAdd(scope.$index, scope.row)">批量</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination v-bind:child-msg="pageParams" @callFather="callFather"/>


    <el-drawer
      title="编辑"
      :visible.sync="drawer"
      :before-close="handleClose">
      <div>
        <el-form label-width="100px" ref="addForm" :model="addForm" :rules="rules">
          <el-form-item label="请求名称" prop="requestName">
            <el-input size="small" v-model="addForm.requestName" auto-complete="off" placeholder="请输入请求名称"/>
          </el-form-item>
          <el-form-item label="请求地址" prop="requestUrl">
            <el-input size="small" v-model="addForm.requestUrl" auto-complete="off" placeholder="请输入请求地址"/>
          </el-form-item>
          <el-form-item label="请求方式" prop="requestMethod">
            <el-select size="small" v-model="addForm.requestMethod" placeholder="请输入请求方式">
              <el-option v-for="type in ['POST', 'GET', 'PUT', 'DELETE']" :label="type" :value="type"
                         :key="type"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="参数类型" prop="requestParams">
            <el-select size="small" v-model="addForm.requestParams" placeholder="请选择参数类型">
              <el-option v-for="type in ['JSON(Filter)', 'JSON', 'LIST(JSON)']" :label="type" :value="type" :key="type"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-row>
              <el-button size="small" type="cancel" :loading="loading" class="title" @click="drawer = false">取消
              </el-button>
              <el-button size="small" type="primary" :loading="loading" class="title" @click="submitForm('addForm')">
                保存
              </el-button>
            </el-row>
          </el-form-item>
        </el-form>
      </div>
    </el-drawer>

  </div>
</template>

<script>
import {
  apiAdd,
  apiEdit,
  apiList,
  datasourceList,
  dbSchamaList,
  pstnList,
  queueAll,
  surveyList
} from "../../../api/baseMG";
import Pagination from '../../../components/Pagination'
import {TaskSave} from "../../../api/cti";
import {getStore} from "../../../utils/util";

export default {
  data() {
    return {
      list: [],
      drawer: false,
      editFormVisible: false,
      addFormVisible: false,
      editTitle: "",
      loading: false,
      editForm: {
        transType: 2,
        maxConcurrentNum: 1
      },
      addForm: {
        transType: 2,
        maxConcurrentNum: 1
      },
      rules: {},
      // 分页参数
      pageParams: {
        currentPage: 1,
        pageSize: 10,
        total: 10
      },
      searchParams: {
        page: 1,
        perPage: 10,
        orderBy: "create_at desc",
        filters: [
          {
            showAble: true,
            readonly: false,
            placeholder: "表名",
            fieldName: "tableName",
            compare: "like",
            fieldValue: ""
          },
          {
            showAble: true,
            readonly: false,
            placeholder: "接口地址",
            fieldName: "requestUrl",
            compare: "like",
            fieldValue: ""
          }
        ],
        isLock: ''
      },
      pstns: [],
      queueNames: [],
      sources: [],
      showSchema: false,
      schemaList: []
    }
  },
  created() {
    this.search();
    this.initQueueNames();
  },
  // 注册组件
  components: {
    Pagination
  },
  methods: {
    sourceChange() {
      this.sources.forEach(r => {
        if(r.id == this.addForm.sourceId && r.dbType == 2 ) {
          this.showSchema = true;
        }
      })
      console.log(this.addForm.sourceId);
      if(this.showSchema) {
        dbSchamaList({id: this.addForm.sourceId}, {}).then(resp => {
          this.schemaList = resp.data.list;
        })
      }
    },
    initSource() {
      datasourceList({}).then(resp => {
        this.sources = resp.data.list;
      })
    },
    submitForm() {
      let that = this;
      this.$refs["addForm"].validate(valid => {
        if (valid) {
          console.log(that.addForm)
          if (!that.addForm.id) {
            apiAdd(that.addForm).then(resp => {
              if (resp.success) {
                this.$message({
                  type: 'success',
                  message: resp.msg
                });
                this.drawer = false;
                this.selectAllApi();
              } else {
                this.$message({
                  type: 'error',
                  message: resp.msg
                });
              }
            })
          } else {
            apiEdit(that.addForm).then(resp => {
              if (resp.success) {
                this.$message({
                  type: 'success',
                  message: resp.msg
                });
                this.drawer = false;
                this.selectAllApi();
              } else {
                this.$message({
                  type: 'error',
                  message: resp.msg
                });
              }
            })
          }

        }
      });
    },
    handleClose() {
      this.drawer = false;
    },
    initQueueNames() {
      let that = this;
      queueAll().then(resp => {
        for (let i = 0; i < resp.data.length; i++) {
          let d = resp.data[i];
          that.queueNames.push({id: d.queueNum, name: d.queueName})
        }
      })
    },
    handleSelect(item) {
      this.editForm.surveyId = item.id;
      this.editForm.surveyName = item.name;
    },
    querySearchAsync(queryString, cb) {
      surveyList({
        page: 1,
        perPage: 10,
        filters: [
          {fieldName: "companyId", compare: "=", fieldValue: getStore("userInfo").companyId},
          {fieldName: "name", compare: "like", fieldValue: queryString},
          {fieldName: "state", compare: "=", fieldValue: 2}
        ],
        isLock: ''
      }).then(resp => {
        this.selectProjectList = resp.data.list;
        for (let i = 0; i < this.selectProjectList.length; i++) {
          this.selectProjectList[i].value = this.selectProjectList[i].name;
        }
        cb(this.selectProjectList);
      })
    },
    getPstnList() {
      pstnList({
        perPage: 1000,
        filters: [],
        isLock: ''
      }).then(resp => {
        this.pstns = resp.data.list;
      })
    },
    // 关闭编辑、增加弹出框
    closeDialog(dialog) {
      if (dialog === 'editForm') {
        this.editFormVisible = false
      } else if (dialog === 'addForm') {
        this.addFormVisible = false
      } else if (dialog === 'unit') {
        this.unitAccessshow = false
      }
    },
    // 分页插件事件
    callFather(param) {
      this.searchParams.page = param.currentPage;
      this.searchParams.perPage = param.pageSize;
      this.getList(this.searchParams);
    },
    handleEdit(index, row) {
      this.addForm = row;
      this.drawer = true;
    },
    handleAdd: function (index, row) {
      this.addForm = JSON.parse(JSON.stringify(row));
      this.addForm.id = null;
      this.addForm.requestName = '批量' + this.addForm.requestName;
      let requestUrl = this.addForm.requestUrl;
      let i = requestUrl.lastIndexOf("/");
      requestUrl = requestUrl.substr(0, i) + "/batch/" + requestUrl.substr(i + 1);
      this.addForm.requestUrl = requestUrl;
      this.drawer = true;
    },
    search() {
      this.getList(this.searchParams);
    },
    getList(params) {
      apiList(params).then(resp => {
        if (resp.success) {
          this.list = resp.data.list;
          this.pageParams.currentPage = resp.data.pageNum;
          this.pageParams.pageSize = resp.data.pageSize;
          this.pageParams.total = resp.data.total;
        }
      })
    }
  }
}
</script>

<style scoped>
.user-search {
  margin-top: 20px;
}

.userRole {
  width: 100%;
}
</style>
